package cn.zoujiedev.netty.core.handler;

import cn.zoujiedev.netty.core.bean.Header;
import cn.zoujiedev.netty.core.bean.MessageType;
import cn.zoujiedev.netty.core.bean.NettyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @Classname HeartbeatRespHandler
 * @Description
 * @Date 2022-11-3 16:35
 * @Created by zoujie
 */
@Slf4j
public class HeartbeatRespHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    Header header = message.getHeader();

    if(header != null && header.getType() == MessageType.HEARTBEAT_REQUEST){
      log.info("Received client heartbeat message : ---> {}",message);

      NettyMessage heartbeatResp = buildHeartbeatResp();
      ctx.writeAndFlush(heartbeatResp);
      log.info("Send heartbeat response message to client : ---> {}",heartbeatResp);
    }else {
      ctx.fireChannelRead(msg);
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.fireExceptionCaught(cause);
  }

  private NettyMessage buildHeartbeatResp(){
    NettyMessage message = new NettyMessage();

    Header h = new Header();
    h.setType(MessageType.HEARTBEAT_RESPONSE);

    message.setHeader(h);
    return message;
  }
}
